﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NMF.Optimizations
{
    public class ObservableSource<T> : ObservableSourceBase<T>, IObservableSource<T>
    {
        private ICollection<T> items;

        public ObservableSource() : this(new HashSet<T>()) { }

        public ObservableSource(ICollection<T> items)
        {
            if (items == null) items = new HashSet<T>();

            this.items = items;
        }

        public void Refresh(T item)
        {
            OnUpdatedItem(item);
        }

        public void RefreshAll()
        {
            foreach (var item in this)
            {
                OnUpdatedItem(item);
            }
        }

        public virtual void Publish(T item)
        {
            items.Add(item);
            OnNewItem(item);
        }

        public virtual void Reset()
        {
            items.Clear();
            OnReset();
        }

        public bool Contains(T item)
        {
            return items.Contains(item);
        }

        public int Count
        {
            get { return items.Count; }
        }

        public virtual bool Revoke(T item)
        {
            if (items.Remove(item))
            {
                OnDeletedItem(item);
                return true;
            }
            else
            {
                return false;
            }
        }

        public override IEnumerator<T> GetEnumerator()
        {
            return items.GetEnumerator();
        }
    }
}
